import React, { useState, useEffect } from 'react';
import { Table, Card, Form, DatePicker, InputNumber, Button, Space, message } from 'antd';
import { useNavigate } from 'react-router-dom';
import moment from 'moment';
import axios from 'axios';

function MyFunds() {
  const [funds, setFunds] = useState([]);
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();

  useEffect(() => {
    fetchMyFunds();
  }, []);

  const fetchMyFunds = async () => {
    try {
      setLoading(true);
      const response = await axios.get('http://localhost:5000/api/user/funds', {
        headers: {
          Authorization: `Bearer ${localStorage.getItem('token')}`
        }
      });
      setFunds(response.data);
    } catch (error) {
      message.error('获取自选基金失败');
    } finally {
      setLoading(false);
    }
  };

  const onAddMonitorRule = async (values, fundId) => {
    try {
      await axios.post(
        'http://localhost:5000/api/monitor/rule',
        {
          fund_id: fundId,
          rule_type: values.rule_type,
          threshold: values.threshold,
          start_date: values.start_date.format('YYYY-MM-DD'),
          end_date: values.end_date?.format('YYYY-MM-DD')
        },
        {
          headers: {
            Authorization: `Bearer ${localStorage.getItem('token')}`
          }
        }
      );
      message.success('添加监控规则成功');
    } catch (error) {
      message.error('添加监控规则失败');
    }
  };

  const columns = [
    {
      title: '基金代码',
      dataIndex: 'code',
      key: 'code',
    },
    {
      title: '基金名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '购买日期',
      dataIndex: 'buy_date',
      key: 'buy_date',
    },
    {
      title: '预期收益率',
      dataIndex: 'expected_rate',
      key: 'expected_rate',
      render: (rate) => `${rate}%`,
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button type="primary" onClick={() => navigate(`/fund/${record.code}`)}>
            查看详情
          </Button>
          <Button onClick={() => showMonitorModal(record.id)}>
            添加监控
          </Button>
        </Space>
      ),
    },
  ];

  const showMonitorModal = (fundId) => {
    // 这里可以实现一个Modal来添加监控规则
    // 为了简化，这里直接使用Form
    const [form] = Form.useForm();
    
    return (
      <Form form={form} onFinish={(values) => onAddMonitorRule(values, fundId)}>
        <Form.Item
          name="rule_type"
          label="规则类型"
          rules={[{ required: true }]}
        >
          <InputNumber min={0} max={100} />
        </Form.Item>
        
        <Form.Item
          name="threshold"
          label="阈值"
          rules={[{ required: true }]}
        >
          <InputNumber min={0} max={100} />
        </Form.Item>
        
        <Form.Item
          name="start_date"
          label="开始日期"
          rules={[{ required: true }]}
        >
          <DatePicker />
        </Form.Item>
        
        <Form.Item
          name="end_date"
          label="结束日期"
        >
          <DatePicker />
        </Form.Item>
        
        <Form.Item>
          <Button type="primary" htmlType="submit">
            确定
          </Button>
        </Form.Item>
      </Form>
    );
  };

  return (
    <Card title="我的基金">
      <Table
        columns={columns}
        dataSource={funds}
        rowKey="id"
        loading={loading}
      />
    </Card>
  );
}

export default MyFunds; 